package Netty.NIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.CountDownLatch;

public class SocketChannelTest {
    static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args) throws IOException {


        for (int i = 0; i < 2; i++) {
//            new Thread(() -> {
                try {
                    run();
                } catch (Exception e) {
                    e.printStackTrace();
                }
//            }, String.format("线程【%s】", i + 1)).start();
//            countDownLatch.countDown();
        }
        System.out.println();

    }

    public static void run() throws IOException, InterruptedException {
        SocketChannel socketChannel = SocketChannel.open();
//        countDownLatch.await();
        socketChannel.connect(new InetSocketAddress("localhost", 9090));

        // 发送请求
        ByteBuffer buffer = ByteBuffer.wrap("1234567890".getBytes());
        socketChannel.write(buffer);

        // 读取响应
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        int num;
        if ((num = socketChannel.read(readBuffer)) > 0) {
            readBuffer.flip();

            byte[] re = new byte[num];
            readBuffer.get(re);

            String result = new String(re, "UTF-8");
            System.out.println("返回值: " + result);
        }
        socketChannel.close();
//        // 发送请求
//         buffer = ByteBuffer.wrap("1234567890".getBytes());
//        socketChannel.write(buffer);
//
//        // 读取响应
//         readBuffer = ByteBuffer.allocate(1024);
//   
//        if ((num = socketChannel.read(readBuffer)) > 0) {
//            readBuffer.flip();
//
//            byte[] re = new byte[num];
//            readBuffer.get(re);
//
//            String result = new String(re, "UTF-8");
//            System.out.println("返回值: " + result);
//        }
    }
}